import type { MyWebSocket } from "@/interface/store";
import { webSocketLogger, logger, CODE } from "@/utils/log";
import { globalData } from "@/store";
import os from "os";

// ! 获取服务端 ip
export function getIpAddress() {
  const ifaces: any = os.networkInterfaces();

  for (var dev in ifaces) {
    let iface = ifaces[dev];

    for (let i = 0; i < iface.length; i++) {
      let { family, address, internal } = iface[i];

      if (family === "IPv4" && address !== "127.0.0.1" && !internal) {
        return address;
      }
    }
  }
}

// !WebSocket 发送封装
export const sendWs_util = (
  ws: MyWebSocket,
  data: any,
  msg: string = "操作成功",
  code: number = 200
) => {
  const sendData = JSON.stringify({
    code,
    msg,
    data,
  });

  ws.send(sendData);
  webSocketLogger.info(`发 ${ws.id} ${sendData}`);
};

//! WebSocket 向指定 id 发送
export const sendWs_id_util = (
  id: string | undefined,
  data: any,
  msg: string = "操作成功",
  code: number = 200
) => {
  const wss = globalData.getWss();
  wss?.clients.forEach((client: MyWebSocket) => {
    if (id && client?.id === id && client.readyState === 1) {
      sendWs_util(client, data, msg, code);
    }
  });
};

//! WebSocket 向全部 发送
export const sendWs_all_util = (
  data: any,
  msg: string = "操作成功",
  code: number = 200
) => {
  const wss = globalData.getWss();
  wss?.clients.forEach((client: MyWebSocket) => {
    if (client.readyState === 1) {
      sendWs_util(client, data, msg, code);
    }
  });
};


/**
 * ! 模糊搜索
 * @param list 原数组
 * @param keyWord 查询的关键词
 * @param attribute 数组需要检索的字段
 * @returns 搜索后结果
 * ?例子：fuzzyQuery_util(arr, '树', 'name') // [{id: 1, name: '树哥'}]
 */
export const fuzzyQuery_util = (
  list: any[],
  keyWord: string,
  attribute: string
) => {
  const reg = new RegExp(keyWord);
  const arr:any[] = [];
  for (let i = 0; i < list.length; i++) {
    if (reg.test(list[i][attribute])) {
      arr.push(list[i]);
    }
  }
  return arr;
};
